# -*- coding: utf-8 -*-            
# @Author : chenliang
# @Time : 2024/10/26 13:58
import requests
import json
from dateutil import parser


class Zentao(object):

    def search_token(self,content_text=''):
        url = "http://www.czyl888.com:9999/zentao/api.php/v1/tokens"
        # 消息内容
        message = {
            "account": "chenliang",
            "password": "Chenliang123"

        }
        # 发送请求
        response = requests.post(url, data=json.dumps(message), headers={'Content-Type': 'application/json'})

        # 打印响应
        return response.text

    def search_bugs(self,token,id='47',status='',limit='100'):

        url = f'http://www.czyl888.com:9999/zentao/api.php/v1/products/{id}/bugs'
        params = {'status': status,'limit':limit}
        try:
            # 发起GET请求
            response = requests.get(url, params=params,headers=json.loads(token))

            # 检查状态码是否为200，即请求成功
            if response.status_code == 200:
                print("请求成功")
                # 返回响应内容（这里以JSON为例）
                return response.json()
            else:
                print(f"请求失败，状态码：{response.status_code}")
                return None
        except Exception as e:
            print(f"发生错误：{e}")
            return None

    def group_bugs_by_assignee(self,bug_data):
        grouped = {}
        for bug in bug_data['bugs']:
            if bug['assignedTo']:
                assignee = bug['assignedTo']['realname']
            else:
                assignee = 'closed'
            if assignee not in grouped:
                grouped[assignee] = []
            grouped[assignee].append({
                'id': bug['id'],
                'title': bug['title'],
                'status': bug['statusName'],
                'priority': f"P{bug['pri']}",
                'create_time': self.parse_iso_time(bug['openedDate']),
                'closedDate': self.parse_iso_time(bug['closedDate']) if bug.get('closedDate') else None
                #'create_time': bug['openedDate']
                ##'url': f"https://bug-system.com/bug/{bug['id']}"
            })
        return grouped

    def group_bugs_by_assignee_list(self, bug_data_list):
        """将多个产品的Bug数据合并后按负责人分组"""
        grouped = {}

        # 遍历每个产品的Bug数据列表
        for product_bugs in bug_data_list:
            # 遍历当前产品的每个Bug
            for bug in product_bugs.get('bugs', []):
                # 提取负责人信息
                assignee = 'closed'  # 默认值
                if bug.get('assignedTo'):
                    assignee = bug['assignedTo'].get('realname', 'unassigned')

                # 创建分组条目
                grouped.setdefault(assignee, [])

                # 构造Bug信息
                bug_info = {
                    'id': bug['id'],
                    'title': bug['title'],
                    'status': bug['statusName'],
                    'priority': f"P{bug['pri']}",
                    'create_time': self.parse_iso_time(bug['openedDate']),
                    'closedDate': self.parse_iso_time(bug['closedDate']) if bug.get('closedDate') else None
                }

                grouped[assignee].append(bug_info)

        return grouped

    # 时间格式化工具
    def parse_iso_time(self,iso_str):

        return parser.parse(iso_str).strftime('%Y-%m-%d')


if __name__ == "__main__":
    content_text = """
    车辆
    换行
    """
    token=Zentao().search_token()
    print(token)
    result=Zentao().search_bugs(token=token,status='all')
    print(result)
    str=Zentao().group_bugs_by_assignee(result)
    #print(str)



